package com.example.demo.common.exceptionHandler;


import com.example.demo.enums.CodeEnum;
import com.example.demo.entity.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLSyntaxErrorException;

/**
 * 捕捉全局未被捕获的异常
 * */
@RestControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionHandlerAdvice {

    @ExceptionHandler(IllegalAccessException.class)
    public ResponseInfo<String> handlerException(IllegalAccessException e){
        log.error(e.getMessage());
        return ResponseInfo.errorInfo(CodeEnum.INTERNAL_ERROR.getCode(),CodeEnum.INTERNAL_ERROR.getMessage(),e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseInfo<String> handlerException(IllegalArgumentException e){
        log.error(e.getMessage());
        return ResponseInfo.errorInfo(CodeEnum.INTERNAL_ERROR.getCode(),CodeEnum.INTERNAL_ERROR.getMessage(),e.getMessage());
    }

//    @ExceptionHandler(NullPointerException.class)
//    public ResponseInfo handlerException(NullPointerException e){
//        log.error(e.getMessage());
//        return ResponseInfo.errorInfo(CodeEnum.INTERNAL_ERROR.getCode(),CodeEnum.INTERNAL_ERROR.getMessage(),e.getMessage());
//    }
    @ExceptionHandler(SQLSyntaxErrorException.class)
    public ResponseInfo<String> handlerException(SQLSyntaxErrorException e){
        log.error(e.getMessage());
        return ResponseInfo.errorInfo(CodeEnum.SQL_ERROR.getCode(),CodeEnum.SQL_ERROR.getMessage(),e.getMessage());
    }
    @ExceptionHandler(RuntimeException.class)
    public ResponseInfo handlerException(RuntimeException e){
        log.error(e.getMessage());
        return ResponseInfo.errorInfo(CodeEnum.INTERNAL_ERROR.getCode(),CodeEnum.INTERNAL_ERROR.getMessage(),e.getMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseInfo<String> handlerException(HttpRequestMethodNotSupportedException e){
        log.error(e.getMessage());
        return ResponseInfo.errorInfo(CodeEnum.METHOD_ERROR.getCode(),CodeEnum.METHOD_ERROR.getMessage(),e.getMessage());
    }
}
